<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\WorkMoment\Action\Dashboard;

use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\WorkMoment\Queue\MomentCommentQueue;
use MoChat\Plugin\WorkMoment\Queue\MomentQueue;
use MoChat\Plugin\WorkMoment\Queue\MomentTaskQueue;

/**
 * 企微朋友圈-同步.
 *
 * Class SynMoment.
 * @Controller
 */
class Sync extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var MomentQueue
     */
    protected $momentQueue;

    /**
     * @Inject
     * @var MomentTaskQueue
     */
    protected $momentTaskQueue;

    /**
     * @Inject
     * @var MomentCommentQueue
     */
    protected $momentCommentQueue;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workMoment/sync", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 异步处理
        try {
            // 企业全部的发表列表
            $this->momentQueue->handle($user['corpIds'][0]);
            // 企业发表的朋友圈成员执行情况
            $this->momentTaskQueue->handle($user['corpIds'][0]);
            // 客户朋友圈的互动数据
            $this->momentCommentQueue->handle($user['corpIds'][0]);
        } catch (InvalidConfigException|GuzzleException $e) {
            $this->logger->error('客户朋友圈同步失败' . $e->getMessage());
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
